package com.sigmatrix.h5.utils.security;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class KeyHelper {

    private final static Map<Integer, String> digestKeyMap = new HashMap<>();

    @Autowired
    private ApplicationContext applicationContext;

    @PostConstruct
    public void initDigestKeyMap() throws IOException {
        int i = 0;
        InputStream in = applicationContext.getResource("classpath:etrace-digest-keys.txt").getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
        String key = null;
        while ((key = reader.readLine()) != null) {
            digestKeyMap.put(i, key);
            i++;
        }
        reader.close();
    }

    /**
     * 随机获取一个key
     * 
     * @return
     */
    public static int randomDigestKeyIndex() {
        return ThreadLocalRandom.current().nextInt(1000);
    }

    /**
     * 获取index 指定的key
     * 
     * @param index
     * @return
     */
    public static String getSpecifiedKey(int index) {
        return digestKeyMap.get(index);
    }
}
